<template>
    <div class="dept-admin">
        <a-button type="primary" class="btn-add" @click="onAdd">新增部门</a-button>
        <a-table :columns="columns" :data-source="list" rowKey="id"
            bordered
            class="dept-table"
            :pagination="pagination"
            @change="onPageChange"
            :loading="loading"
        >
            <span slot="action" slot-scope="text, record">
                <span class="action-btn" @click="onEdit(record)">修改</span>
                <span class="action-btn" @click="onDelete(record.id, record.deptname)">删除</span>
            </span>
        </a-table>
        <a-modal :title="type==='add' ? '新增部门' : '修改部门'" :footer="null" :visible="visible"
            @cancel="onCancel"
        >
            <a-form :form="form" @submit="onSubmit">
                <a-form-item label="部门名称"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-input placeholder="请输入部门名称"
                        v-decorator="['deptname',
                            { rules: [
                                { required: true, message: '请输入部门名称' },
                            ] }
                        ]"
                    ></a-input>
                </a-form-item>
                <a-form-item label="上级部门"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-select placeholder="请选择上级部门"
                        v-decorator="['superiordepartment',
                            { rules: [
                                { required: true, message: '请选择上级部门' },
                            ] }
                        ]"
                    >   
                        <a-select-option :value="0">无</a-select-option>
                        <a-select-option v-for="(item, index) in deptList" 
                            :key="index" :value="item.id"
                        >{{item.deptname}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item :wrapper-col="{offset: 6}">
                    <a-button type="primary" html-type="submit" :loading="addLoading">提交</a-button>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
import { getDeptInfo, getAllDepts, addDept, updateDept, deleteDept } from '@/services';

const columns = [
    { title: '部门名称', dataIndex: 'deptname', align: 'center' },
    { title: '上级部门', dataIndex: 'superiorName', align: 'center' },
    { title: '操作', key: 'action', align: 'center', scopedSlots: { customRender: 'action' } },
]

export default {
    name: 'DeptAdmin',
    data(){
        return {
            visible: false,
            addLoading: false,
            type: '',
            columns,
            formItemLayout: {
                labelCol: { span: 6 },
                wrapperCol: { span: 16 },
            },
            pagination: {},
            loading: false,
            list: [
                { id: 1, deptname: "测试部", name: "总公司"},
                { id: 2, deptname: "质量部", name: "总公司"}
            ],
            deptList: [],
            editId: '',
        }
    },
    beforeMount(){
        this.form = this.$form.createForm(this)
    },
    mounted(){
        this.getDeptList();
        this.getAllDeptList();
    },
    methods: {
        // 新增按钮
        onAdd(){
            this.visible = true;
            this.type = "add"
        },
        // 关闭modal
        onCancel(){
            this.visible = false;
            this.form.resetFields();
        },
        // 删除按钮
        onDelete(id, text){
            const _that = this;
            this.$confirm({
                title: `确认删除 ${text} 吗? `,
                okText: "删除",
                okType: 'danger',
                cancelText: "取消",
                onOk(){
                    _that.onDeleteDept(id)
                }
            })
        },
        // 获取所有部门
        async getAllDeptList(){
            let res = await getAllDepts();
            if(res.responseObject) {
                this.deptList = res.responseObject;
            }
        },
        // 获取部门列表
        async getDeptList(page=1){
            this.loading = true;
            let _data = { page: page }
            let res = await getDeptInfo(_data);
            this.loading = false;
            if(res.responseObject){
                let pagination = { ...this.pagination };
                const { data, count } = res.responseObject
                this.list = data;
                pagination.total = count;
                pagination.current = page;
                pagination.pageSize = 10;
                pagination.showTotal = (total, range) => `共找到 ${total} 条数据`
                this.pagination = pagination;

            }
        },
        // 切换分页
        onPageChange(pagination, filters, sorter){
            let { current, pageSize } = pagination;
            this.getDeptList(current);
        },
        // 提交按钮
        onSubmit(e){
            e.preventDefault();
            const _that = this;
            const { type, editId } = this;
            this.form.validateFields((err, values) => {
                if (!err) {
                    let _item = _that.deptList.filter(item => item.id === values.superiordepartment);
                    let name = _item[0] && _item[0].deptname || "无";
                    let _data = Object.assign(values, { superiorName: name })
                    // 新增部门
                    if(type === 'add') _that.onAddDept(_data);
                    // 修改部门
                    if(type === 'edit') {
                        _data = Object.assign(_data, { id: editId });
                        _that.editDept(_data)
                    }
                }
            })
        },
        // 新增部门
        async onAddDept(params){
            this.addLoading = true;
            let res = await addDept(params);
            this.addLoading = false;
            const _that = this;
            if(res.success){
                this.$message.success('新增部门成功', 1, ()=>{
                    _that.onCancel()
                    _that.getDeptList(_that.pagination.current);
                })
            }else if(res.errorMessage){
                this.$message.error(res.errorMessage, 1)
            }
        },
        // 修改按钮
        onEdit(params){
            this.form.getFieldDecorator('deptname');
            this.form.getFieldDecorator('superiordepartment');
            this.type = 'edit';
            this.visible = true;
            this.editId = params.id;
            this.form.setFieldsValue({
                deptname: params.deptname,
                superiordepartment: params.superiordepartment,
            })
        },
        // 修改部门
        async editDept(params){
            this.addLoading = true;
            let res = await updateDept(params);
            this.addLoading = false;
            const _that = this;
            if(res.success){
                this.$message.success('修改部门成功', 1, ()=>{
                    _that.onCancel();
                    _that.getDeptList(_that.pagination.current);
                })
            }else if(res.errorMessage){
                this.$message.error(res.errorMessage, 1)
            }
        },
        // 删除部门
        async onDeleteDept(id){
            this.loading = true;
            let res = await deleteDept(id);
            const _that = this;
            if(res.success){
                this.$message.success('删除部门成功', 1, ()=>{
                    _that.getDeptList(_that.pagination.count > 11 ? _that.pagination.current : 1);
                })
            }else if(res.errorMessage){
                this.loading = false;
                this.$message.error(res.errorMessage, 1)
            }
        }
    }
}
</script>
<style lang="less" scpoed>
@import '../global.less';
    .dept-admin{
        padding: 20px;
        .btn-add{
            margin-bottom: 20px;
        }
        .dept-table{
            width: 800px;
        }
        .action-btn{
            color: @primary;
            margin: 0 10px;
            cursor: pointer;
        }
    }
</style>